package com.itheima.gatewayadmin.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import com.sun.media.jfxmedia.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AdminAuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取请求过来的URI地址
        String path = request.getURI().getPath();
        log.debug("请求的地址是：{}" , path);
        //2.判断地址是否后台的登录地址
        if (path.startsWith("/admin/login")){
            //是否放行
            return chain.filter(exchange);
        }

        //token校验
        //1.获取token
        String token = request.getHeaders().getFirst("token");
        //2.进行非空判断
        if (StringUtils.isNotEmpty(token)){
            int verifyToken = AppJwtUtil.verifyToken(token);
            if (SystemConstants.JWT_OK == verifyToken){
                return chain.filter(exchange);
            }
        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
